package com.jkt.rms.dataservice.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;

import com.jkt.rms.business.ModuleMaster;
import com.jkt.rms.business.SystemRole;
import com.jkt.rms.commons.utils.ExceptionFactory;
import com.jkt.rms.commons.utils.RMSException;
import com.jkt.rms.dataservice.AbstractDataService;
import com.jkt.rms.dataservice.RoleDataService;

public class RoleDataServiceImpl extends AbstractDataService<SystemRole> implements RoleDataService  {

	private static final Logger LOG = Logger.getLogger(UIModuleLinkupDataServiceImpl.class);
	@Override
	protected Class<SystemRole> getReferenceClass() {
		return SystemRole.class;
	}

	public void evictCollection(String collectionId) {
		getSessionFactory().evictCollection(collectionId);
	}
	
	@Override
	public SystemRole isRoleExist(String userName) {
		
		Criteria criteria = getSession().createCriteria(getReferenceClass());
		SystemRole roleExist = (SystemRole) criteria.add(
				Restrictions.eq(SystemRole.PROP_ROLE_NAME, userName))
				.uniqueResult();
		return roleExist;
	}
	
	@Override
	public SystemRole saveRole(SystemRole sysrole) {
		SystemRole sysRole = save(sysrole);
		return sysRole;
	}
	
	@Override
	public void saveorUpdateRole(SystemRole sysrole) throws RMSException {
		saveOrUpdate(sysrole);
		
	}
	
	@SuppressWarnings("unchecked")
	public List<SystemRole> findAll() {
		
		List<SystemRole> roles = new ArrayList<SystemRole>();
		String hql ="from SystemRole";
		Query query = getSession().createQuery(hql);
		roles = query.list();
		return roles;
	}
	
	public List<String> findAllRoleNames() {
		List<String> roles = new ArrayList<String>();
		try
		{
			String hql ="select role_name from sysrole_master sm";
			Query query = getSession().createSQLQuery(hql).addScalar("role_name", Hibernate.STRING);;
			query.setCacheable(true);
			roles =   query.list();
			return roles;
		}
		catch(Exception e)
		{
			ExceptionFactory.createRMSException(LOG, e.getCause());
			return roles;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ModuleMaster> findAllModules() {
		String hql ="from ModuleMaster mu";
		Query query = getSession().createQuery(hql);
		query.setCacheable(true);
		List<ModuleMaster> modules = new ArrayList<ModuleMaster>();
		modules   = (List<ModuleMaster>)query.list();
		return modules;
	}
	
	public ModuleMaster getModuleById(int module_id){
		return (ModuleMaster)getHibernateTemplate().load(ModuleMaster.class, module_id);
	}
}
